//
//  YCCamera.swift
//  YCCamera
//
//  Created by Billy on 2024/4/15.
//

import UIKit
import AVFoundation
import SnapKit
import Photos
import CoreMotion
import CoreImage
import CoreMedia
import UniformTypeIdentifiers
import MetalKit
import ObjectiveC

open class YCCamera: UIViewController, UIGestureRecognizerDelegate {
    
    // MARK: - Managers
    private lazy var sessionManager: YCCameraSessionManager = {
        let manager = YCCameraSessionManager(processingQueue: processingQueue)
        manager.delegate = self
        return manager
    }()
    
    private let photoLibraryManager = YCPhotoLibraryManager()
    
    // MARK: - Legacy Support (保留兼容旧代码)
    enum Layout {
        static let bottomViewH: CGFloat = YCCameraConstants.Layout.bottomViewHeight
        static let topInset: CGFloat = 0
        static let largeCircleRadius: CGFloat = YCCameraConstants.Layout.largeCircleRadius
        static let smallCircleRadius: CGFloat = YCCameraConstants.Layout.smallCircleRadius
        static let largeCircleRecordScale: CGFloat = YCCameraConstants.Layout.largeCircleRecordScale
        static let smallCircleRecordScale: CGFloat = YCCameraConstants.Layout.smallCircleRecordScale
        static let borderLayerWidth: CGFloat = YCCameraConstants.Layout.borderLayerWidth
        static let animateLayerWidth: CGFloat = YCCameraConstants.Layout.animateLayerWidth
        static let previewRadius: CGFloat = YCCameraConstants.Layout.previewCornerRadius
        static let cameraBtnNormalColor: UIColor = YCCameraConstants.Colors.cameraButtonNormal
        static let cameraBtnRecordingBorderColor: UIColor = YCCameraConstants.Colors.cameraButtonRecordingBorder
    }
    
    public lazy var tipsLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 14)
        label.textColor = .white
        label.textAlignment = .center
        label.numberOfLines = 2
        label.lineBreakMode = .byWordWrapping
        label.alpha = 0
        return label
    }()
    
    /// 相机画面
    public lazy var displayView: UIView = {
        let view = UIView();
        view.backgroundColor = .black
        view.layer.cornerRadius = YCCamera.Layout.previewRadius
        view.layer.masksToBounds = true
        
        return view
    }()
    
    private lazy var bottomView: YCCameraBottomView = {
        let view = YCCameraBottomView()
        view.delegate = self
        
        return view
    }()
        
//    private lazy var controlView: UIView = {
//        let view = UIView()
//        view.backgroundColor = .clear
//        return view
//    }()
        
    private lazy var focusCursorView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "yc_focus"))
        view.contentMode = .scaleAspectFit
        view.clipsToBounds = true
        view.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
        view.alpha = 0
        
        return view
    }()
    
    /// 获取相册最新的照片（使用 PhotoLibraryManager）
    func getLatestPhoto() {
        // 显示加载状态
        bottomView.latestPhoto.alpha = YCCameraConstants.PhotoLibrary.thumbnailLoadingAlpha
        
        photoLibraryManager.getLatestPhoto { [weak self] image in
                    guard let self = self, let thumbnail = image else { return }
                    
                            self.bottomView.latestPhoto.image = thumbnail
            UIView.animate(withDuration: YCCameraConstants.PhotoLibrary.thumbnailFadeDuration) {
                self.bottomView.latestPhoto.alpha = YCCameraConstants.PhotoLibrary.thumbnailFinalAlpha
            }
        }
    }
    
    // MARK: - Device Motion
    private var motionManager: CMMotionManager?
    private var orientation: AVCaptureVideoOrientation = .portrait
    
    // MARK: - State
    private var isAdjustingFocusPoint = false
    private var isTakingPicture = false
    private var takedImage: UIImage?
        
    private lazy var focusCursorTapGes: UITapGestureRecognizer = {
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(adjustFocusPoint))
        tap.delegate = self
        return tap
    }()
    
    private lazy var pinchGes: UIPinchGestureRecognizer = {
        let pin = UIPinchGestureRecognizer(target: self, action: #selector(pinchToAdjustCameraFocus(_:)))
        return pin
    }()
    
    private lazy var filterNameLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .systemFont(ofSize: 16, weight: .medium)
        label.textAlignment = .center
        label.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        label.layer.cornerRadius = 8
        label.layer.masksToBounds = true
        label.alpha = 0
        return label
    }()
    
    // 添加属性来跟踪当前的滤镜图层
    private var currentFilterLayer: CALayer?
    
    // 存储当前处理后的图像
    private var currentProcessedImage: CIImage?
    
    // 帧处理和滤镜切换状态
    private var isProcessingFrame = false  // 控制帧处理
    private var isChangingFilter = false   // 控制滤镜切换
    
    private var initialTouchPoint: CGPoint = .zero
    
    private var lastFilterNameUpdate: TimeInterval = 0
    private var isShowingFilterName = false
    
    private lazy var shutterAnimationView: UIView = {
        let view = UIView()
        view.backgroundColor = .black
        view.alpha = 0
        return view
    }()
    
    private var feedbackGenerator: UIImpactFeedbackGenerator?
    
    private lazy var topShutterView: UIView = {
        let view = UIView()
        view.backgroundColor = .black
        view.isHidden = true
        return view
    }()
    
    private lazy var bottomShutterView: UIView = {
        let view = UIView()
        view.backgroundColor = .black
        view.isHidden = true
        return view
    }()
    
    // 添加 Metal 相关属性
    private lazy var metalView: MTKView = {
        let view = MTKView()
        return view
    }()
    
    private var commandQueue: MTLCommandQueue?
    private var ciContext: CIContext?
    
    // 添加信号量来控制帧处理
    private let renderingSemaphore = DispatchSemaphore(value: 1)
    private let processingQueue = DispatchQueue(label: "com.yc.camera.processing", qos: .userInteractive)
    
    // 缓存变换矩阵和渲染尺寸
    private var lastDrawableSize: CGSize = .zero
    private var lastTransform: CGAffineTransform?
    
    // 添加性能监控
    private var frameCount: Int = 0
    private var lastFrameTime: CFTimeInterval = 0
    
    private var manualController: YCCameraManualController?
    
    // 滤镜选择视图
    private var filterSelectionView: YCFilterSelectionView?
    
    // 仅支持竖屏显示
    override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    override public var prefersStatusBarHidden: Bool {
        return true
    }
    
    override open func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        // 停止会话
        sessionManager.stopSession()
        
        // 执行关闭动画
        YCCameraAnimationManager.performShutterCloseAnimation(
            topView: topShutterView,
            bottomView: bottomShutterView,
            containerBounds: displayView.bounds
        )
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupMetal()
        
        // 配置相机会话
        sessionManager.setupSession()
        
        // 请求权限
        checkAndRequestPermissions { [weak self] granted in
            if granted {
                // 在后台线程加载最新照片
                DispatchQueue.global(qos: .userInitiated).async {
            self?.getLatestPhoto()
                }
            } else {
                self?.showPermissionDeniedAlert()
            }
        }
        
        // 注册应用生命周期通知
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }
    
    private func checkAndRequestPermissions(completion: @escaping (Bool) -> Void) {
        let group = DispatchGroup()
        var cameraGranted = false
        var photoGranted = false
        
        // 检查相机权限
        group.enter()
        AVCaptureDevice.requestAccess(for: .video) { granted in
            cameraGranted = granted
            group.leave()
        }
        
        // 检查相册权限
        group.enter()
        if #available(iOS 14, *) {
            PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in
                photoGranted = status == .authorized || status == .limited
                group.leave()
            }
        } else {
            PHPhotoLibrary.requestAuthorization { status in
                photoGranted = status == .authorized
                group.leave()
            }
        }
        
        group.notify(queue: .main) {
            completion(cameraGranted && photoGranted)
        }
    }
    
    private func showPermissionDeniedAlert() {
        let alert = UIAlertController(
            title: "需要权限",
            message: "请在设置中允许访问相机和相册权限，以便使用拍照功能。",
            preferredStyle: .alert
        )
        
        alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(settingsURL)
            }
        })
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        
        DispatchQueue.main.async {
            self.present(alert, animated: true)
        }
    }
    
    @objc func applicationWillResignActive(notification: NSNotification) {
        if(self.isViewLoaded && (self.view.window != nil)){
            debugPrint("*进入后台---------由当前应用跳到其他应用APP*")
            
        }
    }
    
    @objc func applicationDidBecomeActive(notification: NSNotification) {
        if(self.isViewLoaded && (self.view.window != nil)){
            debugPrint("*进入前台--------由另一个程序回到当前程序应用*")

        }
    }
    
    @objc func applicationWillEnterForeground(notification: NSNotification) {
        if(self.isViewLoaded && (self.view.window != nil)){
            debugPrint("*即将进入前台--------由另一个程序回到当前程序应用*")
            
            guard sessionManager.isRunning else {
                return
            }
        }
    }
    
    override open func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        observerDeviceMotion()
        
        // 仅在需要时获取最新照片
        if bottomView.latestPhoto.image == nil {
            getLatestPhoto()
        }
        
        // 启动相机会话
        sessionManager.startSession()
    }
    
    override open func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 延迟执行相机启动动画，确保所有布局都完成
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
            guard let self = self else { return }
            YCCameraAnimationManager.performShutterOpenAnimation(
                topView: self.topShutterView,
                bottomView: self.bottomShutterView,
                containerBounds: self.displayView.bounds
            )
        }
    }
    
    override open func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        // 由于使用了AutoLayout，displayView的frame已经自动确定
        // 只需要更新依赖displayView bounds的子视图
        
        let shutterHeight = displayView.bounds.height / 2
        
        // 始终更新frame尺寸，但不重置transform（避免干扰动画）
        if topShutterView.layer.animationKeys()?.isEmpty ?? true {
            // 只有在没有动画进行时才更新frame
            topShutterView.frame = CGRect(x: 0, y: 0, width: displayView.bounds.width, height: shutterHeight)
            bottomShutterView.frame = CGRect(x: 0, y: shutterHeight, width: displayView.bounds.width, height: shutterHeight)
        } else {
            // 如果有动画在进行，只更新尺寸
            var topFrame = topShutterView.frame
            topFrame.size = CGSize(width: displayView.bounds.width, height: shutterHeight)
            topShutterView.frame = topFrame
            
            var bottomFrame = bottomShutterView.frame
            bottomFrame.size = CGSize(width: displayView.bounds.width, height: shutterHeight)
            bottomShutterView.frame = bottomFrame
        }
        
        // 更新拍照快门动画视图的frame
        shutterAnimationView.frame = displayView.bounds
    }
    
    private func setupUI() {
        view.backgroundColor = YCCameraConstants.Colors.primaryBackground
        
        // 先添加bottomView并确定其高度
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-BottomSafeHeight)
            make.height.equalTo(Layout.bottomViewH)  // 固定高度180pt
        }
        
        // 再添加displayView，基于bottomView的位置确定
        view.addSubview(displayView)
        
        // 计算displayView的约束 - 保持4:3比例，底部贴紧bottomView顶部
        let scale: CGFloat = 4 / 3
        displayView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.width.equalToSuperview()  // 宽度等于屏幕宽度
            make.height.equalTo(displayView.snp.width).multipliedBy(scale)  // 高度 = 宽度 * 4/3
            make.bottom.equalTo(bottomView.snp.top)  // 底部贴紧bottomView顶部
        }
        
        // 添加 Metal 视图
        displayView.addSubview(metalView)
        metalView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 聚焦光标视图添加到 displayView 上层（在相机画面之上）
        displayView.addSubview(focusCursorView)
        
        // 拍照快门动画视图添加到 displayView 上层（能盖住光标和相机画面）
        displayView.addSubview(shutterAnimationView)
        
        // 相机启动盖子视图添加到最上层（能盖住所有内容，相当于相机的盖子）
        displayView.addSubview(topShutterView)
        displayView.addSubview(bottomShutterView)
        
        // 初始化震动反馈生成器
        feedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
        feedbackGenerator?.prepare()
                
        // 添加聚焦点击手势
        displayView.addGestureRecognizer(focusCursorTapGes)
        // 添加缩放手势
        displayView.addGestureRecognizer(pinchGes)
        
//        view.addSubview(controlView)
//        controlView.snp.makeConstraints { make in
//            make.left.right.equalToSuperview()
//            make.bottom.equalTo(bottomView.snp.top)
//            make.height.equalTo(150)
//        }
        
        // 添加滤镜名称标签
        view.addSubview(filterNameLabel)
        filterNameLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top).offset(-20)
            make.width.equalTo(100)
            make.height.equalTo(30)
        }
        
        // 暂时注释掉平移手势，使用点击滤镜按钮的方式切换滤镜
        // 添加平移手势
//        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleFilterPan(_:)))
//        panGesture.delegate = self
//        displayView.addGestureRecognizer(panGesture)
    }
    
    /// 监听设备运动方向
    private func observerDeviceMotion() {
        if !Thread.isMainThread {
            YCMainAsync {
                self.observerDeviceMotion()
            }
            return
        }
        
        motionManager = CMMotionManager()
        // 更新时间
        motionManager?.deviceMotionUpdateInterval = 0.5
        if motionManager?.isDeviceMotionAvailable == true {
            motionManager?.startDeviceMotionUpdates(to: .main, withHandler: { motion, _ in
                if let motion = motion {
                    self.handleDeviceMotion(motion)
                }
            })
        } else {
            motionManager = nil
        }
    }
    
    func handleDeviceMotion(_ motion: CMDeviceMotion){
        let x = motion.gravity.x
        let y = motion.gravity.y
        
        if abs(y) >= abs(x) || abs(x) < 0.45 {
            if y >= 0.45 {
                // 屏幕朝下，对应的照片方向为UIImageOrientationLeft
                orientation = .portraitUpsideDown
                rotateUI(by: .pi)
            } else {
                // 屏幕朝上，对应的照片方向为UIImageOrientationRight
                orientation = .portrait
                UIView.animate(withDuration: 0.15) {
                    self.bottomView.flashBtn.transform = CGAffineTransformIdentity
                    self.bottomView.switchCameraBtn.transform = CGAffineTransformIdentity
                    self.bottomView.latestPhoto.transform = CGAffineTransformIdentity
                }
            }
        } else {
            if x >= 0 {
                // 屏幕朝左横屏，对应的照片方向为UIImageOrientationUp
                orientation = .landscapeLeft
                rotateUI(by: .pi / 2 * 3)
            } else {
                // 屏幕朝右横屏，对应的照片方向为UIImageOrientationDown
                orientation = .landscapeRight
                rotateUI(by: .pi / 2 )
            }
        }
    }
    
    private func rotateUI(by angel: CGFloat) {
        
        UIView.animate(withDuration: 0.15) {
            self.bottomView.flashBtn.transform = CGAffineTransform(rotationAngle: angel)
            self.bottomView.switchCameraBtn.transform = CGAffineTransform(rotationAngle: angel)
            self.bottomView.latestPhoto.transform = CGAffineTransform(rotationAngle: angel)
        } completion: { Bool in
            
        }
    }
    
    // 已删除：setupCamera, getCamera, refreshSessionPreset, addAudioInput, getMicrophone, removeAudioInput
    // 这些功能现在由 YCCameraSessionManager 处理
    
    /// 拍照
    
    @objc private func adjustFocusPoint(_ tap: UITapGestureRecognizer) {
        guard !isAdjustingFocusPoint else { return }
        
        let point = tap.location(in: displayView)
        setfocusCusor(point: point)
    }
    
    @objc private func pinchToAdjustCameraFocus(_ pinch: UIPinchGestureRecognizer) {
        guard let device = sessionManager.getCurrentDevice() else { return }
        
        var zoomFactor = device.videoZoomFactor * pinch.scale
        zoomFactor = max(1, min(zoomFactor, sessionManager.getMaxZoomFactor()))
        sessionManager.setZoomFactor(zoomFactor)
    
        pinch.scale = 1
    }
    
    private func setfocusCusor(point: CGPoint) {
        isAdjustingFocusPoint = true
        
        // 执行聚焦动画
        YCCameraAnimationManager.performFocusAnimation(
            view: focusCursorView,
            at: point
        ) { [weak self] in
            self?.isAdjustingFocusPoint = false
        }
        
        // 转换为相机坐标（使用 displayView 的相对坐标）
        let normalizedX = point.x / displayView.bounds.width
        let normalizedY = point.y / displayView.bounds.height
        let cameraPoint = CGPoint(x: normalizedX, y: normalizedY)
        
        // 设置聚焦点
        sessionManager.setFocusPoint(cameraPoint)
    }
    
    private var shutterSpeedUpdateTimer: Timer?
    
    /// 设置快门速度（带防抖动处理）
    /// - Parameter value: 0.0 - 1.0
    func setShutterSpeed(_ value: Float) {
        // 取消之前的定时器
        shutterSpeedUpdateTimer?.invalidate()
        
        // 创建新的定时器，延迟应用快门速度
        shutterSpeedUpdateTimer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false) { [weak self] _ in
            self?.manualController?.setShutterSpeed(value)
        }
    }
    
    // 暂时注释掉滑动切换滤镜功能
    // 添加滤镜滑动相关属性
//    private var initialPanPoint: CGFloat = 0  // 记录滑动起始位置
//    private let filterChangeThreshold: CGFloat = 50  // 切换滤镜的距离阈值
    
//    @objc private func handleFilterPan(_ gesture: UIPanGestureRecognizer) {
//        let translation = gesture.translation(in: displayView)
//
//        switch gesture.state {
//        case .began:
//            // 记录滑动起始位置
//            initialPanPoint = translation.x
//            // 重置滤镜切换状态
//            isChangingFilter = false
//
//        case .changed:
//            // 如果正在切换滤镜，则不再处理
//            guard !isChangingFilter else { return }
//
//            // 计算滑动距离
//            let distance = translation.x - initialPanPoint
//
//            // 当滑动距离超过阈值时切换滤镜
//            if abs(distance) >= filterChangeThreshold {
//                // 标记正在切换滤镜
//                isChangingFilter = true
//
//                // 触发震动反馈
//                feedbackGenerator?.impactOccurred(intensity: 0.3)
//                feedbackGenerator?.prepare()
//
//                // 直接切换滤镜
//                if distance < 0 {
//                    YCFilterManager.shared.nextFilter()
//                } else {
//                    YCFilterManager.shared.previousFilter()
//                }
//
//                // 显示滤镜名称
//                showFilterName()
//
//                // 添加滤镜切换动画效果
//                animateFilterChange(direction: distance < 0 ? .left : .right)
//
//                // 延迟重置滤镜切换状态，允许动画完成
//                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
//                    self?.isChangingFilter = false
//                }
//
//                // 重置起始点，避免连续触发
//                initialPanPoint = translation.x
//            }
//
//        case .ended, .cancelled:
//            // 如果未正在切换滤镜且滑动距离超过阈值的一半，触发切换
//            if !isChangingFilter {
//                let finalDistance = translation.x - initialPanPoint
//                if abs(finalDistance) >= filterChangeThreshold / 2 {
//                    // 标记正在切换滤镜
//                    isChangingFilter = true
//
//                    // 触发震动反馈
//                    feedbackGenerator?.impactOccurred(intensity: 0.3)
//                    feedbackGenerator?.prepare()
//
//                    // 直接切换滤镜
//                    if finalDistance < 0 {
//                        YCFilterManager.shared.nextFilter()
//                    } else {
//                        YCFilterManager.shared.previousFilter()
//                    }
//
//                    // 显示滤镜名称
//                    showFilterName()
//
//                    // 添加滤镜切换动画效果
//                    animateFilterChange(direction: finalDistance < 0 ? .left : .right)
//
//                    // 延迟重置滤镜切换状态，允许动画完成
//                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
//                        self?.isChangingFilter = false
//                    }
//                }
//            }
//
//        default:
//            break
//        }
//    }
    
    // 添加滤镜切换方向枚举
    private enum FilterChangeDirection {
        case left
        case right
    }
    
    // 添加滤镜切换动画效果
    private func animateFilterChange(direction: FilterChangeDirection) {
        // 创建一个临时视图来显示动画效果
        let animationView = UIView(frame: displayView.bounds)
        animationView.backgroundColor = UIColor.black.withAlphaComponent(0.2)
        displayView.addSubview(animationView)
        
        // 设置初始位置（从屏幕边缘开始）
        let screenWidth = displayView.bounds.width
        animationView.transform = CGAffineTransform(translationX: direction == .left ? screenWidth : -screenWidth, y: 0)
        
        // 执行动画
        UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseOut], animations: {
            animationView.transform = .identity
        }) { _ in
            UIView.animate(withDuration: 0.2) {
                animationView.alpha = 0
            } completion: { _ in
                animationView.removeFromSuperview()
            }
        }
    }
    
    // 显示滤镜名称
    private func showFilterName() {
        let filterName = YCFilterManager.shared.getCurrentFilterName()
        YCCameraAnimationManager.showFilterName(label: filterNameLabel, text: filterName)
    }
    
    deinit {
        // 清理震动生成器
        feedbackGenerator = nil
    }
    
    // MARK: - 已删除的动画方法
    // animateShutterClose 和 animateShutterOpen 已由 YCCameraAnimationManager 处理
    
    // 确保手势识别器可以同时工作
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, 
                                shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 允许平移手势与其他手势同时工作
        if gestureRecognizer is UIPanGestureRecognizer && 
           (otherGestureRecognizer is UITapGestureRecognizer || 
            otherGestureRecognizer is UIPinchGestureRecognizer) {
            return true
        }
        return false
    }
    
    private func setupMetal() {
        guard let device = MTLCreateSystemDefaultDevice() else {
            fatalError("Metal is not supported on this device")
        }
        
        // 配置 Metal 视图
        metalView.device = device
        metalView.delegate = self
        metalView.framebufferOnly = false
        metalView.enableSetNeedsDisplay = true
        metalView.isPaused = true
        metalView.preferredFramesPerSecond = 30
        metalView.autoResizeDrawable = true
        metalView.presentsWithTransaction = false
        metalView.colorPixelFormat = .bgra8Unorm
        metalView.clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
        
        // 配置命令队列
        commandQueue = device.makeCommandQueue()
        
        // 配置 CoreImage 上下文
        let options: [CIContextOption: Any] = [
            .outputColorSpace: CGColorSpaceCreateDeviceRGB(),
            .workingColorSpace: CGColorSpaceCreateDeviceRGB(),
            .useSoftwareRenderer: false,
            .cacheIntermediates: false,
            .name: "YCCameraContext"
        ]
        
        ciContext = CIContext(mtlDevice: device, options: options)
    }
}

extension YCCamera: YCCameraBottomViewDelegate {
    
    /// 拍照
    func cameraDidClick(_bottomView: YCCameraBottomView) {
        guard !isTakingPicture else { return }
        
        isTakingPicture = true
        
        // 确定闪光灯模式
        let flashMode: AVCaptureDevice.FlashMode = (sessionManager.hasFlash() && bottomView.flashBtn.isSelected) ? .auto : .off
        
        // 执行拍照
        sessionManager.capturePhoto(flashMode: flashMode, orientation: orientation)
    }
    
    /// 闪光灯
    func flashDidClick(_bottomView: YCCameraBottomView, isOn: Bool) {
        
    }
    
    /// 切换摄像头
    func switchCameraDidClick(_bottomView: YCCameraBottomView) {
        sessionManager.switchCamera { success in
            if success {
                print("✅ 切换摄像头成功")
                } else {
                print("❌ 切换摄像头失败")
            }
        }
    }
    
    /// 画面比例选择
    func aspectSelectDidClick(_bottomView: YCCameraBottomView) {
        
    }
    
    /// 定时
    func timeSelectDidClick(_bottomView: YCCameraBottomView) {
        
    }
    
    /// 滤镜选择
    func filterDidClick(_bottomView: YCCameraBottomView) {
        // 如果已经存在滤镜选择视图且正在显示，直接关闭
        if let existingView = filterSelectionView, existingView.superview != nil {
            existingView.dismiss()
            return
        }
        
        // 如果不存在滤镜选择视图，创建新的（只创建一次）
        if filterSelectionView == nil {
            let selectionView = YCFilterSelectionView()
            selectionView.delegate = self
            filterSelectionView = selectionView
        }
        
        // 显示滤镜选择视图（保持之前的选中状态）
        filterSelectionView?.show(in: self.view)
    }

    /// 最新照片
    func latestPhotoTapped(_bottomView: YCCameraBottomView) {
        // 创建相册视图控制器
        let galleryVC = YCGalleryViewController() // 临时替换，等待实现
        // 创建导航控制器
        let navController = UINavigationController(rootViewController: galleryVC)
        navController.modalPresentationStyle = .fullScreen
        // 呈现相册
        present(navController, animated: true, completion: nil)
    }
}

// MARK: - YCCameraSessionDelegate（相机会话回调）
extension YCCamera: YCCameraSessionDelegate {
    func cameraSession(_ manager: YCCameraSessionManager, willCapturePhoto: Void) {
        // 播放拍照快门动画
        YCCameraAnimationManager.performPhotoFlashAnimation(view: shutterAnimationView)
        
        // 触发震动反馈
        feedbackGenerator?.impactOccurred(intensity: 0.5)
        feedbackGenerator?.prepare()
    }
    
    func cameraSession(_ manager: YCCameraSessionManager, didCapturePhoto image: UIImage, ciImage: CIImage) {
        isTakingPicture = false
        
        // 应用滤镜和镜像处理
        let isFrontCamera = sessionManager.currentPosition == .front
        var processedImage = image
        
        if let filteredImage = YCFilterManager.shared.processCapturedImage(ciImage, orientation: orientation, isFrontCamera: isFrontCamera) {
            processedImage = filteredImage.yc.fixOrientation()
        }
        
        // 更新UI显示
        takedImage = processedImage
        bottomView.latestPhoto.image = processedImage
        
        // 执行缩略图动画
        YCCameraAnimationManager.performLatestPhotoAnimation(
            imageView: bottomView.latestPhoto,
            image: processedImage
        )

        // 保存到相册（使用 PhotoLibraryManager）
        photoLibraryManager.savePhotoWithMetadata(
            processedImage,
            flashOn: bottomView.flashBtn.isSelected,
            device: sessionManager.getCurrentDevice()
        ) { [weak self] success, error in
                            if success {
                // 清除缓存，下次会加载最新照片
                self?.photoLibraryManager.invalidateCache()
                            } else if let error = error {
                print("❌ 保存照片失败: \(error.localizedDescription)")
                            }
                        }
                    }
    
    func cameraSession(_ manager: YCCameraSessionManager, didOutput sampleBuffer: CMSampleBuffer) {
        // 处理每一帧视频
        processVideoFrame(sampleBuffer)
                }
            }

// MARK: - CAAnimationDelegate 已删除
// 动画完成回调现在由 YCCameraAnimationManager 中的 completion 闭包处理

extension YCCamera {
    /// 设置 ISO
    /// - Parameter value: 0.0 - 1.0
    func setISO(_ value: Float) {
        manualController?.setISO(value)
    }
    
    /// 设置白平衡
    /// - Parameters:
    ///   - temperature: 0.0 - 1.0
    ///   - tint: -1.0 - 1.0
    func setWhiteBalance(temperature: Float) {
        manualController?.setWhiteBalance(temperature: temperature)
    }
    
    /// 重置为自动模式
    func resetCameraSettings() {
        manualController?.resetToAutoMode()
    }
    
    private func YCMainAsync(_ block: @escaping () -> Void) {
        if Thread.isMainThread {
            block()
        } else {
            DispatchQueue.main.async(execute: block)
        }
    }
}

// MARK: - Video Frame Processing（视频帧处理）
extension YCCamera {
    /// 由 YCCameraSessionDelegate 触发，处理每一帧视频
    private func processVideoFrame(_ sampleBuffer: CMSampleBuffer) {
        guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
        
        autoreleasepool {
            // 创建CIImage
            let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
            let currentFilterName = YCFilterManager.shared.getCurrentFilterName()
            
            // 处理图像并在主线程更新UI
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                
                if currentFilterName == "原图" {
                    self.currentProcessedImage = ciImage
                } else {
                    if let filteredImage = YCFilterManager.shared.processPreviewImage(ciImage) {
                        self.currentProcessedImage = filteredImage
                    } else {
                        self.currentProcessedImage = ciImage
                    }
                }
                
                // 触发 Metal 重绘
                self.metalView.setNeedsDisplay()
            }
        }
    }
}

extension YCCamera: YCFilterSelectionViewDelegate {
    func filterSelectionView(_ view: YCFilterSelectionView, didSelectFilter filterName: String) {
        // 滤镜已经在选择视图中切换了，触发画面更新
        print("切换到滤镜: \(filterName)")
        
        // 触发metalView重绘以应用新滤镜
        DispatchQueue.main.async {
            self.metalView.setNeedsDisplay()
        }
        
        // 显示滤镜名称提示
        showFilterName()
    }
}

extension YCCamera: MTKViewDelegate {
    public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
        lastDrawableSize = size
        lastTransform = nil
    }
    
    public func draw(in view: MTKView) {
        guard let drawable = view.currentDrawable,
              let commandBuffer = commandQueue?.makeCommandBuffer(),
              let ciContext = ciContext,
              let currentImage = currentProcessedImage else {
            return
        }
        
        autoreleasepool {
            // 获取当前帧的尺寸
            let drawableSize = view.drawableSize
            
            // 检查是否需要重新计算变换
            if drawableSize != lastDrawableSize || lastTransform == nil {
                let imageSize = currentImage.extent.size
                let drawableBounds = CGRect(x: 0, y: 0, width: drawableSize.width, height: drawableSize.height)
                
                // 计算适当的缩放比例，保持宽高比
                let scaleX = drawableBounds.width / imageSize.width
                let scaleY = drawableBounds.height / imageSize.height
                let scale = min(scaleX, scaleY) // 使用min而不是max，确保图像完全显示
                
                let scaledWidth = imageSize.width * scale
                let scaledHeight = imageSize.height * scale
                let x = (drawableBounds.width - scaledWidth) / 2
                let y = (drawableBounds.height - scaledHeight) / 2
                
                lastTransform = CGAffineTransform.identity
                    .translatedBy(x: x + scaledWidth/2, y: y + scaledHeight/2)
                    .scaledBy(x: scale, y: scale)
                    .translatedBy(x: -imageSize.width/2, y: -imageSize.height/2)
                
                lastDrawableSize = drawableSize
            }
            
            // 使用缓存的变换
            let transformedImage = currentImage.transformed(by: lastTransform!)
            
//            print("Drawable size: \(drawableSize)")
//            print("Transformed image bounds: \(transformedImage.extent)")
            
            // 清除渲染目标
            let renderPassDescriptor = view.currentRenderPassDescriptor
            renderPassDescriptor?.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
            renderPassDescriptor?.colorAttachments[0].loadAction = .clear
            
            // 创建渲染命令编码器
            if let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor!) {
                renderEncoder.endEncoding()
            }
            
            // 渲染图像
            ciContext.render(transformedImage,
                           to: drawable.texture,
                           commandBuffer: commandBuffer,
                           bounds: CGRect(origin: .zero, size: drawableSize),
                           colorSpace: CGColorSpaceCreateDeviceRGB())
            
            // 提交并显示
            commandBuffer.present(drawable)
            commandBuffer.commit()
        }
    }
}


